package com.ant.capter08;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;

/**
 * 将指令编码
 */
public class PacketCodeC {
    private static final int MAGIC_NUMBER = 0X12345678;

    /**
     * 将指令编码
     * @param p
     * @return
     */
    public ByteBuf encode(Package p){
        ByteBuf buf = ByteBufAllocator.DEFAULT.buffer();
        final byte[] bytes = SerializerAlgorithm.DEFAULT.serialize(p);
        //1.魔数
        buf.writeInt(MAGIC_NUMBER);
        //2.版本号
        buf.writeByte(p.getVersion());
        //3.序列化算法
        buf.writeByte(SerializerAlgorithm.JSON);
        //4.指令类型
        buf.writeByte(p.getCommand());
        //5.数据长度
        buf.writeInt(bytes.length);
        //6.数据
        buf.writeBytes(bytes);
        return buf;
    }

    /**
     * 将指令字节数组解码成指令对象
     * @param buf
     * @return
     */
    public Package decode(ByteBuf buf){
        //魔数
        int magic = buf.readInt();
        //版本号
        final byte version = buf.readByte();
        //序列化算法
        final byte algorithm = buf.readByte();
        //指令类型
        final byte command = buf.readByte();
        //数据长度
        final int length = buf.readInt();
        //数据
        byte[] bs = new byte[length];
        buf.readBytes(bs);
        final Serializer serializer = SerializerAlgorithm.getSerializer(algorithm);
        final Class<? extends Package> packageType = Command.getPackageType(command);
        return serializer.deserialize(packageType, bs);
    }
}
